import request from './request.js';
import store from './store.js';

document.addEventListener('DOMContentLoaded', () => {
    // 如果已经登录，直接跳转到主页
    if (store.state.isLogin) {
        window.location.href = 'index.html';
        return;
    }

    const loginForm = document.getElementById('loginForm');
    const loginBtn = loginForm.querySelector('.login-btn');

    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();

        // 禁用登录按钮
        loginBtn.disabled = true;
        loginBtn.innerHTML = '<span class="btn-text">登录中...</span>';

        try {
            // 发送登录请求
            const loginRes = await request({
                url: '/api/user/login',
                method: 'post',
                data: {
                    userAccount: username,
                    userPassword: password
                }
            });

            // 获取用户信息
            const userRes = await request({
                url: '/api/user/get/login',
                method: 'get'
            });

            // 保存用户信息
            store.setCurrentUser(userRes.data);
            
            // 显示成功动画
            loginBtn.innerHTML = '<span class="btn-icon">🎉</span> 登录成功';
            loginForm.classList.add('success');
            
            // 延迟跳转
            setTimeout(() => {
                window.location.href = 'index.html';
            }, 750);

        } catch (error) {
            console.error('登录失败:', error);
            alert(error.message || '登录失败，请重试');
            
            // 恢复按钮状态
            loginBtn.disabled = false;
            loginBtn.innerHTML = '<span class="btn-text">开启惊喜</span>';
        }
    });

    // 检查 URL 参数中的消息
    const urlParams = new URLSearchParams(window.location.search);
    const message = urlParams.get('message');
    if (message) {
        alert(message);
        // 清除 URL 参数
        window.history.replaceState({}, '', 'login.html');
    }
});